import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)


// 2. 定义路由
const routes = [
  {
    path: "/",
    // 后台管理系统重定向到登录页面
    redirect: "/login"
  },
  {
    path: '/login',
    component: () => import("../views/login.vue")
  },
  {
    path: '/layout',
    component: () => import("@/views/layout.vue"),
    redirect: "/layout/index",
    children: [
      {
        path: "index",
        component: () => import("@/views/index.vue")
      },
      {
        path: "articleList",
        component: () => import("@/views/articleList.vue")
      },
      {
        path: "articleAdd",
        component: () => import("@/views/articleAdd.vue")
      }
    ]
  },
]

// 3. 创建 router 实例，然后传 `routes` 配置
const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
})

// 配置导航守卫
// 除了登录页面，其他页面都必须登录后才能访问
// 登录后，当用户访问登录页面的时候，自动跳转首页
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token_backend")
  if (to.path !== '/login' && !token) {
    next("/login")
  } else {
    // 登录后，不让用户访问登录页面，直接跳转到首页即可
    if (token && to.path == "/login") {
      next("/layout")
    } else {
      next()
    }
  }
})


// 4 导出
export default router